package cn.kz.keepass_android;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import cn.kz.keepass_android.util.Constant;
import cn.kz.keepass_android.util.KeepassUtil;
import cn.kz.keepass_android.util.SPUtil;
import cn.kz.keepass_android.util.StringUtils;

/**
 * Created by kz on 2017/3/8.
 */
public class SettingActivity extends AppCompatActivity implements View.OnClickListener {
    private static int FILE_SELECT_CODE = 11;
    private TextView dbChooser;
    private Button saveSettingsBtn;
    private EditText server, password;
    private CheckBox remember_pwd;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setting);

        dbChooser = (TextView) findViewById(R.id.db_chooser);
        saveSettingsBtn = (Button) findViewById(R.id.save_settings);
        server = (EditText) findViewById(R.id.server);
        password = (EditText) findViewById(R.id.password);
        remember_pwd = (CheckBox) findViewById(R.id.remember_pwd);

        String serverAddr = SPUtil.getString(SettingActivity.this, Constant.SERVER_ADDR);
        String dbPath = SPUtil.getString(SettingActivity.this, Constant.DB_PATH);

        if (serverAddr != null) {
            server.setText(serverAddr);
        }
        if (dbPath != null) {
            dbChooser.setText(dbPath);
        }

        dbChooser.setOnClickListener(this);
        saveSettingsBtn.setOnClickListener(this);
    }


    private void showFileChooser() {
        String uri = SPUtil.getString(this, Constant.DB_PATH);
        System.out.println("showFileChooser:" + uri);
        if (uri == null) {
            //get and choose from file
            try {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");      //all files
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), FILE_SELECT_CODE);
            } catch (android.content.ActivityNotFoundException ex) {
                // Potentially direct the user to the Market with a Dialog
                Toast.makeText(this, "Please install a File Manager.", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == FILE_SELECT_CODE) {
                try {
                    Uri uri = data.getData();
                    String[] split = uri.getPath().split(":");
                    String path = Environment.getExternalStorageDirectory() + "/" + split[1];

                    //save to sharedPreferences
                    SPUtil.setString(SettingActivity.this, Constant.DB_PATH, path);

                    dbChooser.setText(path);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.db_chooser:
                showFileChooser();
                break;
            case R.id.save_settings:
                String server_addr = server.getText().toString();
                String pwd = password.getText().toString();
                String dbPath = dbChooser.getText().toString();

                if (!StringUtils.isEmpty(server_addr)) {
                    SPUtil.setString(SettingActivity.this, Constant.SERVER_ADDR, server_addr);
                }

                if (!StringUtils.isEmpty(dbPath)) {
                    SPUtil.setString(SettingActivity.this, Constant.DB_PATH, dbPath);
                }

                if (remember_pwd.isChecked()) {
                    SPUtil.setString(SettingActivity.this, Constant.PASSWORD, pwd);
                }

                try {
                    KeepassUtil.getDB(dbPath, pwd);
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(SettingActivity.this, "无法打开数据库，请验证数据库路径和密码", Toast.LENGTH_LONG).show();
                }

                Toast.makeText(SettingActivity.this, "save success", Toast.LENGTH_SHORT).show();
                break;
        }
    }
}
